<template>
    <div class="h-screen overflow-hidden flex flex-col">
        <div class="p-4 border-b border-gray-200 bg-gray-50 flex items-center">
            <h1 class="text-xl font-bold">Markdown Reader {{ " | " + current_filename }}</h1>

            <button
                class="ml-auto flex items-center justify-center w-10 h-10 rounded-full bg-gray-100 hover:bg-gray-200    transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-gray-300"
                @click="logout">
                <i class="fa fa-power-off text-red-600 hover:text-red-800 transition-colors duration-200"></i>
            </button>

            <button
                class="ml-2 flex items-center justify-center w-10 h-10 rounded-full bg-gray-100 hover:bg-gray-200 transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-blue-300"
                @click="download">
                <i v-if="!isLoading" class="fa fa-download text-blue-600 hover:text-blue-800 transition-colors duration-200"></i>
                <i v-else class="fa fa-circle-o-notch fa-spin text-blue-600"></i>
            </button>

            <button
                class="ml-2 flex items-center justify-center w-10 h-10 rounded-full bg-gray-100 hover:bg-gray-200 transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-gray-300"
                @click="openModal('md')">
                <i class="fa fa-question text-green-600 hover:text-green-800 transition-colors duration-200"></i>
            </button>
        </div>

        <div class="flex flex-1 overflow-hidden">
            <FileTree :width="treeWidth" v-model:markdownContent="markdownContent" />


            <div ref="resizer" class="relative w-1 cursor-col-resize" @mousedown="startResize">
                <div class="absolute inset-y-0 left-0 right-0 bg-gray-300 hover:bg-gray-400 transition-colors"></div>
                <div class="absolute inset-y-0 left-[-10px] right-[-10px] bg-transparent"></div>
            </div>


            <!-- <MarkdownPreview :content="markdownContent" /> -->
            <MarkdownContent :content="markdownContent"></MarkdownContent>
        </div>


        <!-- 模态框组件 -->
        <Modal v-if="isModalOpen" :size="modalSize" @close="closeModal" class="z-0">
            <template #title>
                <h3 class="text-lg font-bold text-gray-800">用户须知</h3>
            </template>
            <template #content>
                <div class="p-4 space-y-4 text-gray-700">
                    <p>欢迎使用 Markdown Reader，本应用可帮助您查看和编辑 Markdown 文档。</p>
                    <p>使用前请确保您已了解以下事项：</p>
                    <ul class="list-disc pl-5 space-y-1">
                        <li>支持标准 Markdown 语法</li>
                        <li>支持简单 Latex 语法</li>
                        <li>支持剪贴板上传图片</li>
                        <li>支持 Markdown 目录导出</li>
                        <li>Ctrl + S: 保存文档内容</li>
                        <li>Ctrl + P: 切换 编辑/预览 模式</li>
                        <li>点击右上角退出按钮可安全登出</li>
                    </ul>
                    <p class="text-sm text-gray-500">如有任何问题，请联系技术支持。</p>
                </div>
            </template>
            <template #footer>
                <button
                    class="px-4 py-2 bg-primary text-white rounded hover:bg-primary/90 transition-colors duration-200"
                    @click="closeModal">
                    我知道了
                </button>
            </template>
        </Modal>

    </div>
</template>

<script setup>

const resizer = ref(null)
const markdownContent = ref('点击左侧文件列表，获取文件')

// 状态管理
const treeWidth = ref(300)
const minTreeWidth = 250
const minContentWidth = 300
const { Message } = useMessageBox()
const current_filename = useState("current_filename")
const { isModalOpen, openModal, closeModal, modalSize } = useModal('md');

// 拖动相关状态
let isResizing = false
let initialX = 0
let initialWidth = 0

const router = useRouter()
const logout = () => {
    useCookie("token").value = null
    router.push('/login')
}

const isLoading = ref(false)
const downloadFile = async() => {
    isLoading.value = true
    try {
        const baseURL = await getMyBaseURL()
        const token = useCookie('token')
        const link = document.createElement('a')
        link.href = `${baseURL}/file/markdown/export?token=${token.value}`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
    } catch (error) {
        Message.error('下载失败', { width: 'auto' })
    } finally {
        setTimeout(() => {
            isLoading.value = false
        }, 1000 + Math.random() * 1000)
    }
}
const download = () => {
    downloadFile()
}

// 开始拖动
const startResize = (e) => {
    e.preventDefault()
    isResizing = true
    initialX = e.clientX
    initialWidth = treeWidth.value

    // 优化拖动时的视觉体验
    document.body.style.cursor = 'col-resize'
    document.body.style.userSelect = 'none'

    // 禁用过渡动画以获得即时响应
    const fileTree = document.querySelector('[style*="width"]')
    if (fileTree) {
        fileTree.style.transition = 'none'
    }
}

// 处理鼠标移动
const handleMouseMove = (e) => {
    if (!isResizing) return

    const width = initialWidth + (e.clientX - initialX)
    if (width >= minTreeWidth && width <= window.innerWidth - minContentWidth) {
        // 直接更新宽度，不使用 requestAnimationFrame
        treeWidth.value = width
    }
}

// 处理鼠标释放
const handleMouseUp = () => {
    if (!isResizing) return

    isResizing = false
    document.body.style.cursor = ''
    document.body.style.userSelect = ''

    // 恢复过渡动画
    const fileTree = document.querySelector('[style*="width"]')
    if (fileTree) {
        fileTree.style.transition = 'width 0.15s ease'
    }
}

onMounted(() => {
    // 添加全局事件监听器
    document.addEventListener('mousemove', handleMouseMove)
    document.addEventListener('mouseup', handleMouseUp)
})


onUnmounted(() => {
    // 组件销毁时移除事件监听器
    document.removeEventListener('mousemove', handleMouseMove)
    document.removeEventListener('mouseup', handleMouseUp)
})

</script>